﻿using log4net;
using Mangox.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mangox.BLL.Stock
{
    public class StockCommBLL
    {

        static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// 邮件发送
        /// </summary>
        public static void SendEmail(string displayName, string title, string body)
        {
            try
            {
                EmailHelper email = new EmailHelper(GetConfig("ToEmailAddress"), title, "<html><body><div style='color:red;'>" + body + "</div></body></html>");
                email.Send(displayName);
                log.InfoFormat("SendEmail：邮件发送成功");
            }
            catch (Exception ex)
            {
                log.ErrorFormat("StockCommBLL/SendEmail：发送失败，displayName-{0}，title-{1}，body-{2}，失败原因：{3}", displayName, title, body, ex);
            }
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfig(string key)
        {
            try
            {
                return ConfigurationManager.AppSettings[key];
            }
            catch (Exception ex)
            {
                log.ErrorFormat("StockCommBLL/GetConfig：key-{0}，fail-{1}", key, ex);
            }
            return null;
        }

        /// <summary>
        /// 更新配置文件，写入配置文件，操作配置文件
        /// 在*.exe.config文件中appSettings配置节增加一对键、值对
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void UpdateAppConfig(string key, string value)
        {
            bool isModified = false;
            foreach (string k in ConfigurationManager.AppSettings)
            {
                if (k == key)
                {
                    isModified = true;
                }
            }

            //打开配置文件
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //删除旧的key
            if (isModified)
            {
                config.AppSettings.Settings.Remove(key);
            }
            //添加key
            config.AppSettings.Settings.Add(key, value);
            //保存app.config文件中的更改
            config.Save(ConfigurationSaveMode.Modified);
            //强制重新加载一个修改过的部分
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 长度不够补空格
        /// 汉字和英文长度不同
        /// </summary>
        /// <param name="str"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string StrLen(string str, int len)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }
            int length = Encoding.GetEncoding("gb2312").GetBytes(str.ToCharArray()).Length;

            if (length < len)
            {
                str = str.PadRight(len - ChineseCount(str), ' ');
            }
            return str;
        }

        /// <summary>
        /// 判断汉字，计算汉字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ChineseCount(string str)
        {
            int num = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if ((int)str[i] > 127)
                    num++;
            }
            return num;
        }


        /// <summary>   
        /// 确认是否有安装某程序    
        /// </summary>   
        /// <param name="appName">包含的名称</param>
        /// <returns>true: 有安装, false:没有安装</returns>   
        public bool CheckAppName(string appName)
        {
            try
            {
                Microsoft.Win32.RegistryKey uninstallNode = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
                foreach (string subKeyName in uninstallNode.GetSubKeyNames())
                {
                    Microsoft.Win32.RegistryKey subKey = uninstallNode.OpenSubKey(subKeyName);
                    object displayName = subKey.GetValue("DisplayName");
                    if (displayName != null)
                    {
                        if (displayName.ToString().Contains(appName))
                        {
                            return true;
                            // MessageBox.Show(displayName.ToString());   
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("StockCommBLL/CheckAppName：appName-{0}，fail-{1}", appName, ex);
            }
            return false;   
        } 
        

        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="str"></param>
        public static void WriteLog(string str)
        {
            if (log.IsInfoEnabled)
                log.Info(str);
        }


    }
}
